package com.tang.model.mouse.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author tangyuan2meicloud.com
 * @DATE 2021/9/7 21:22
 * @Desc
 * @Remarks
 */
/*
    被监听者
    通过反射去调用监听器的回调方法
 */
public class EventContext {
    private Map<String, Event> maps = new HashMap<>();

    public void addListener(String name, EventListener target) throws NoSuchMethodException {
        Method method = target.getClass().getMethod("on" + firstCharUpCase(name), Event.class);
        Event event = new Event(target, name, method);
        maps.put(name, event);
    }

    private String firstCharUpCase(String name) {
        char[] chars = name.toCharArray();
        chars[0] -= 32;
        return new String(chars);
    }

    public void trigger(String method) {
        if (!maps.containsKey(method)) return;
        Event tEvent = maps.get(method);
        trigger(tEvent);
    }

    private void trigger(Event event) {
        event.setSource(this);
        event.setTime(System.currentTimeMillis());
        try {
            Method fallback = event.getFallback();
            fallback.invoke(event.getTarget(), event);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
        }
    }

}
